import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:seedfour/app/models/income_order_list_entity.dart';
import 'package:seedfour/app/theme.dart';
import 'package:seedfour/app/widget/null_tip.dart';

import '../../../constants.dart';
import 'logic.dart';

class OrderIncomePage extends StatelessWidget {
  OrderIncomePage({Key? key}) : super(key: key);

  final logic = Get.find<OrderIncomeLogic>();

  @override
  Widget build(BuildContext context) {
    return Obx(
      () => Scaffold(
        appBar: AppBar(
          title:
              logic.isSearching.value ? _buildSearchField() : const Text('收款'),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 16.w,
            ),
            onPressed: () {
              Get.back();
            },
          ),
          bottom: TabBar(
            controller: logic.tabController,
            tabs: incomeOrderStatus.values
                .map((title) => Tab(text: title))
                .toList(),
          ),
          // 创建收款订单按钮
          actions: [
            if (!logic.isSearching.value) ...[
              IconButton(
                onPressed: () => {logic.onClickSearch()},
                icon: SvgPicture.asset(
                  'assets/icons/ic_search.svg',
                  width: kIconSizeTiny,
                ),
              ),
              IconButton(
                onPressed: () => logic.toCreateOrder(),
                icon: const Icon(Icons.add),
              ),
            ]
          ],
        ),
        body: logic.isLoading.value
            ? const Center(child: CircularProgressIndicator())
            : RefreshIndicator(
                onRefresh: () async => logic.reload(),
                child: Stack(
                  children: [
                    ListView.builder(
                        physics: const AlwaysScrollableScrollPhysics(),
                        controller: logic.scrollController,
                        itemBuilder: _renderRow,
                        itemCount: logic.orderList.length + 2),
                    if (logic.isSearching.value && !logic.isSearched.value)
                      Container(
                        width: double.maxFinite,
                        height: double.maxFinite,
                        color: const Color(0x55000000),
                      ),
                  ],
                ),
              ),
      ),
    );
  }

  Widget _buildSearchField() {
    return Container(
      height: 40.w,
      margin: EdgeInsets.only(right: kSpaceMedium),
      child: TextField(
        autofocus: true,
        controller: logic.searchController,
        keyboardType: TextInputType.text,
        textInputAction: TextInputAction.search,
        onSubmitted: (value) => logic.onSearch(),
        onTap: () => logic.onClickSearch(),
        decoration: InputDecoration(
          prefixIcon: IconButton(
            icon: SvgPicture.asset(
              'assets/icons/ic_search.svg',
              width: kIconSizeTiny,
              height: kIconSizeTiny,
            ),
            onPressed: () => logic.onSearch(),
          ),
          suffixIcon: IconButton(
            iconSize: kIconSizeTiny,
            icon: const Icon(Icons.close),
            onPressed: () => logic.onCancelSearch(),
          ),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(kRadiusMedium),
            borderSide: const BorderSide(color: AppColor.colorBorderGrey),
          ),
          hintText: '对方户名或创建人',
          hintStyle: TextStyle(
            fontSize: kFontSizeSmall,
            color: AppColor.colorFontHint,
          ),
          contentPadding:
              EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.w),
        ),
      ),
    );
  }

  Widget _renderRow(BuildContext context, int index) {
    if (index == 0) {
      return _buildTotalAmount();
    } else if (index < logic.orderList.length + 1) {
      int i = index - 1;
      return Padding(
        padding: EdgeInsets.only(
            left: kSpaceMedium, right: kSpaceMedium, bottom: kSpaceMedium),
        child: ClipRRect(
          borderRadius: BorderRadius.all(Radius.circular(kSpaceSmall)),
          child: Material(
            color: Colors.white,
            child: InkWell(
              onTap: () => logic.toOrderDetail(i),
              child: _buildListItem(logic.orderList[i]),
            ),
          ),
        ),
      );
    } else if (logic.orderList.isEmpty) {
      return Column(
        children: [
          SizedBox(height: kSpaceHuge),
          const NullTip(),
        ],
      );
    } else {
      return _getMoreWidget();
    }
  }

  Widget _buildTotalAmount() {
    return Container(
      width: double.maxFinite,
      padding:
          EdgeInsets.symmetric(horizontal: kSpaceMedium, vertical: kSpaceSmall),
      margin:
          EdgeInsets.symmetric(horizontal: kSpaceSmall, vertical: kSpaceMedium),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(kSpaceSmall),
      ),
      child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
              logic.status.value == 0
                  ? '总计金额(元)'
                  : logic.status.value == 1
                      ? '未到账金额(元)'
                      : '已到账金额(元)',
              style: TextStyle(
                fontSize: kFontSizeMedium,
                color: AppColor.colorFontBlack,
                fontWeight: AppFont.fontRegular,
              ),
            ),
            Text(
              logic.orderListEntity.value!.sumAmount!.replaceAll('¥', ''),
              style: TextStyle(
                fontSize: kFontSizeLarge,
                fontWeight: AppFont.fontMedium,
                color: logic.status.value == 0
                    ? AppColor.colorFontBlack
                    : logic.status.value == 1
                        ? AppColor.colorFontRed
                        : AppColor.colorFontGreen,
              ),
            ),
          ]),
    );
  }

  Widget _buildListItem(IncomeOrderInfo item) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: EdgeInsets.all(kSpaceMedium),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                item.createdAt == null
                    ? ''
                    : DateFormat('yyyy.MM.dd HH.mm').format(
                        DateTime.fromMillisecondsSinceEpoch(item.createdAt!)),
                style: TextStyle(
                  color: AppColor.colorFontBlack,
                  fontSize: kFontSizeMedium,
                  fontWeight: AppFont.fontRegular,
                ),
              ),
              Text(
                item.orderStatus == 0 ? '未到账' : '已到账',
                style: TextStyle(
                  color: item.orderStatus == 0
                      ? AppColor.colorFontRed
                      : AppColor.colorFontGreen,
                  fontSize: kFontSizeMedium,
                  fontWeight: AppFont.fontRegular,
                ),
              ),
            ],
          ),
        ),
        Container(color: AppColor.colorLineGrey, height: 0.5.w),
        SizedBox(height: kSpaceMedium),
        Padding(
          padding: EdgeInsets.symmetric(horizontal: kSpaceMedium),
          child: Text(
            item.title ?? '',
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              fontSize: kFontSizeSmall,
              fontWeight: AppFont.fontRegular,
              color: AppColor.colorFontBlack,
            ),
          ),
        ),
        Padding(
          padding: EdgeInsets.all(kSpaceMedium),
          child: Row(
            children: [
              Text(
                item.orderAmountStr ?? '¥0.00',
                style: TextStyle(
                  fontWeight: AppFont.fontMedium,
                  fontSize: kFontSizeBig,
                  color: AppColor.colorFontBlack,
                ),
              ),
              SizedBox(width: kSpaceMini),
              Container(
                padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 4.w),
                decoration: BoxDecoration(
                  color: AppColor.colorTagBackground,
                  borderRadius: BorderRadius.circular(kSpaceTiny),
                ),
                child: Text(logic.invoiceStatus(item),
                    style: TextStyle(
                      color: AppColor.colorFontBlack,
                      fontSize: kFontSizeTiny,
                      fontWeight: AppFont.fontRegular,
                      height: 1.2,
                    ),
                    overflow: TextOverflow.ellipsis),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _getMoreWidget() {
    return Center(
      child: Padding(
        padding: EdgeInsets.only(bottom: kSpaceMedium),
        child: Text(
          logic.bottomTips.value,
          style: TextStyle(fontSize: kFontSizeSmall, color: Colors.grey),
        ),
      ),
    );
  }
}
